from fastapi import FastAPI
from fastapi.requests import Request
from fastapi.responses import JSONResponse
import os
from multiprocessing import cpu_count

from fastapi.middleware.cors import CORSMiddleware

import api.router
from core.config import settings
from core.exceptions import BaseAPIException
from schema.response import ErrorResponse


app = FastAPI(title=settings.PROJECT_NAME)
app.include_router(api.router.router)


@app.get('/')
async def index():
    return {'status': 'OK'}


app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=False,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.exception_handler(BaseAPIException)
async def user_with_that_email_exist_exception_handler(req: Request, exc: BaseAPIException):
    data = ErrorResponse(exc, req)
    return JSONResponse(data.__dict__, status_code=data.status_code)


if __name__ == '__main__':
    # os.chdir('/lct-krasnodar-2023/lct-krasnodar-2023/')
    if settings.DEBUG is True:
        os.system(f'uvicorn main:app '
                  f'--host {settings.BACKEND_HOST} '
                  f'--port {settings.BACKEND_PORT} '
                  f'--log-level debug '
                  f'--reload')
    else:
        os.system(f'gunicorn main:app \
             --bind 0.0.0.0:{settings.BACKEND_PORT} \
             --workers {cpu_count() * settings.WORKERS_PER_THREAD} \
             -k uvicorn.workers.UvicornWorker')
